package org.lc.cmd.impl.ws;

import lombok.RequiredArgsConstructor;
import org.lc.cmd.CmdProvider;
import org.lc.cmd.CmdSession;
import org.lc.cmd.NeedReplySysReq;
import org.lc.cmd.NoReplySysReq;
import org.lc.cmd.SentSysReq;
import org.lc.cmd.exp.DevException;
import org.lc.cmd.model.SysReqData;
import org.lc.cmd.model.WsData;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@RequiredArgsConstructor
public abstract class WebSocketSession implements CmdSession {
    private final CmdProvider provider;

    protected abstract void sendData(WsData data);

    @Override
    public  <T> Future<T> sendSysReq(SentSysReq<T> req) {
        SysReqData data = req.toTransferData();
        WsData wsData = new WsData();
        wsData.setType("sysReq");
        wsData.setData(provider.jsonUtil().toJson(data));
        sendData(wsData);
        if (req instanceof NoReplySysReq) {
            CompletableFuture<T> future = new CompletableFuture<>();
            future.complete(null);
            return future;
        }
        if (req instanceof NeedReplySysReq) {
            NeedReplySysReq<T> needReplySysReq = (NeedReplySysReq<T>) req;
            return needReplySysReq.createReplyFuture();
        }
        throw new DevException(String.format("Class <%s> should implements NoReplySysReq or NeedReplySysReq", req.getClass().getName()));
    }
}
